package com.zhiyuan.audio;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;

public class AudioDeviceAdapter extends RecyclerView.Adapter<AudioDeviceAdapter.ViewHolder> {
    private List<AudioDevice> devices = new ArrayList<>();
    private OnDeviceClickListener listener;
    private OnDeviceControlListener controlListener;
    private int selectedPosition = -1;

    public interface OnDeviceClickListener {
        void onDeviceClick(AudioDevice device);
    }

    public interface OnDeviceControlListener {
        void onMuteToggle(AudioDevice device);
        void onVolumeChange(AudioDevice device, float volume);
    }

    public void setOnDeviceClickListener(OnDeviceClickListener listener) {
        this.listener = listener;
    }

    public void setOnDeviceControlListener(OnDeviceControlListener controlListener) {
        this.controlListener = controlListener;
    }

    public void addDevice(AudioDevice device) {
        devices.add(device);
        notifyItemInserted(devices.size() - 1);
    }

    public void clearDevices() {
        devices.clear();
        selectedPosition = -1;
        notifyDataSetChanged();
    }

    public void updateDevice(AudioDevice device) {
        for (int i = 0; i < devices.size(); i++) {
            if (devices.get(i).getId().equals(device.getId())) {
                devices.set(i, device);
                notifyItemChanged(i);
                break;
            }
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_audio_device, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        AudioDevice device = devices.get(position);
        holder.bind(device, position == selectedPosition);

        holder.itemView.setOnClickListener(v -> {
            int oldPosition = selectedPosition;
            selectedPosition = position;

            if (oldPosition >= 0) {
                notifyItemChanged(oldPosition);
            }
            notifyItemChanged(selectedPosition);

            if (listener != null) {
                listener.onDeviceClick(device);
            }
        });
    }

    @Override
    public int getItemCount() {
        return devices.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        private TextView tvName, tvType, tvStatus;
        private View indicator;

        // 静音控制组件 - 可选，如果布局文件中没有则为null
        private Button btnMute;
        private SeekBar sbVolume;
        private TextView tvVolumeValue;

        ViewHolder(View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tv_device_name);
            tvType = itemView.findViewById(R.id.tv_device_type);
            tvStatus = itemView.findViewById(R.id.tv_device_status);
            indicator = itemView.findViewById(R.id.view_indicator);

            // 尝试获取静音控制组件，如果不存在则忽略
            try {
                btnMute = itemView.findViewById(R.id.btn_mute);
                sbVolume = itemView.findViewById(R.id.sb_volume);
                tvVolumeValue = itemView.findViewById(R.id.tv_volume_value);
            } catch (Exception e) {
                // 如果布局文件中没有这些组件，设为null
                btnMute = null;
                sbVolume = null;
                tvVolumeValue = null;
            }
        }

        void bind(AudioDevice device, boolean isSelected) {
            tvName.setText(device.getName());
            tvType.setText(device.getType().getDisplayName());

            // 更新状态显示
            String statusText = device.isAvailable() ? "可用" : "不可用";
            if (device.isMuted()) {
                statusText += " (静音)";
            }
            tvStatus.setText(statusText);

            // 设置选中状态
            indicator.setVisibility(isSelected ? View.VISIBLE : View.INVISIBLE);

            // 设置背景色
            int backgroundColor = isSelected ?
                    0xFFE3F2FD : // 浅蓝色
                    0x00000000;  // 透明
            itemView.setBackgroundColor(backgroundColor);

            // 静音按钮 - 只有在组件存在时才设置
            if (btnMute != null) {
                btnMute.setText(device.isMuted() ? "取消静音" : "静音");
                btnMute.setEnabled(device.isMuteSupported());
                btnMute.setOnClickListener(v -> {
                    if (controlListener != null) {
                        controlListener.onMuteToggle(device);
                    }
                });
            }

            // 音量控制 - 只有在组件存在时才设置
            if (sbVolume != null && tvVolumeValue != null) {
                sbVolume.setEnabled(device.isAvailable() && !device.isMuted());
                sbVolume.setProgress((int) (device.getVolume() * 100));
                tvVolumeValue.setText(String.format("%.0f%%", device.getVolume() * 100));

                sbVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                    @Override
                    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                        if (fromUser) {
                            float volume = progress / 100.0f;
                            tvVolumeValue.setText(String.format("%.0f%%", volume * 100));

                            if (controlListener != null) {
                                controlListener.onVolumeChange(device, volume);
                            }
                        }
                    }

                    @Override
                    public void onStartTrackingTouch(SeekBar seekBar) {}

                    @Override
                    public void onStopTrackingTouch(SeekBar seekBar) {}
                });
            }
        }
    }
}